package com.example.deliveryapp;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainPageActivity extends AppCompatActivity {

    private FrameLayout fragmentContainer;
    private BottomNavigationView bottomNavigationView;
    private MainPageFragment mainPageFragment;
    private SearchScreenFragment searchScreenFragment;
    private MyAccountPageFragment myAccountPageFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainpage);

        fragmentContainer = findViewById(R.id.fragment_container);
        bottomNavigationView = findViewById(R.id.bottomNavigationView);

        // 初始化Fragment
        mainPageFragment = new MainPageFragment();
        searchScreenFragment = new SearchScreenFragment();
        myAccountPageFragment = new MyAccountPageFragment();

        // 默认显示主页Fragment
        displayFragment(mainPageFragment);

        // 设置 BottomNavigationView 的监听器
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            int itemId = item.getItemId(); // 获取选项的 ID
            if (itemId == R.id.home) {
                selectedFragment = mainPageFragment;
            } else if (itemId == R.id.search) {
                selectedFragment = searchScreenFragment;
            } else if (itemId == R.id.me) {
                selectedFragment = myAccountPageFragment;
            }
            // 替换 FrameLayout 中的 Fragment
            displayFragment(selectedFragment);
            return true;
        });
    }

    private void displayFragment(Fragment fragment) {
        if (fragment != null && !fragment.isVisible()) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, fragment);
            transaction.addToBackStack(null); // 添加到回退栈
            transaction.commit();
        }
    }

    // 新增方法，用于切换到 MyAccountPageFragment
    public void showMyAccountPageFragment() {
        displayFragment(myAccountPageFragment);
        bottomNavigationView.setSelectedItemId(R.id.me);
    }
}